package com.littlepay.kr4.paulin.dfeba77.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.common.design.MaterialDialog;
import com.littlepay.kr4.paulin.dfeba77.GuideActivity;
import com.littlepay.kr4.paulin.dfeba77.LockActivity;
import com.littlepay.kr4.paulin.dfeba77.LockSettingActivity;
import com.littlepay.kr4.paulin.dfeba77.R;
import com.littlepay.kr4.paulin.dfeba77.UserSettingActivity;
import com.littlepay.kr4.paulin.dfeba77.application.MyApplication;
import com.littlepay.kr4.paulin.dfeba77.utils.DBTransaction;
import com.littlepay.kr4.paulin.dfeba77.utils.PrefUtils;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import static android.widget.Toast.LENGTH_SHORT;

//import static android.content.Context.MODE_PRIVATE;
//import static com.example.john.settings.util.PrefUtils.getSharedPreferences;
//import com.orhanobut.logger.Logger;

/**
 * Created by john on 2017/5/15.
 *
 */

public class SettingFragment extends PreferenceFragment{
    String phone;
    Preference islocked;
    Preference onShowBudget;
    Preference guide;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        final MyApplication application = (MyApplication) getActivity().getApplication();
        addPreferencesFromResource(R.xml.preferences);
        final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager()
                .findPreference("is_continue");
        onShowBudget= (Preference) getPreferenceManager()
                .findPreference(getString(R.string.budget));
        final Preference usersSetting = getPreferenceManager().findPreference(getString(R.string.user_setting));
        final Preference suggestion = getPreferenceManager().findPreference("suggestion");
        guide = getPreferenceManager().findPreference("guide");
        islocked = getPreferenceManager().findPreference("islocked");
        //String s= String.valueOf(application.getBudget());
        onShowBudget.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                final EditText editTextBudget;
                LayoutInflater inflater = LayoutInflater.from(getActivity());
                View view1 = inflater.inflate(R.layout.dialog_budget,null);
                editTextBudget = (EditText) view1.findViewById(R.id.edittext_budget);
                //editTextBudget.requestFocus();
                editTextBudget.setGravity(Gravity.LEFT);
                //转换多余的0，全零则显示hint
                String budget = String.valueOf(Integer.parseInt(PrefUtils.getBudget()));
                if(!budget.equals("0")){
                    editTextBudget.setText(budget);
                }else{
                    editTextBudget.setText("");
                }
                editTextBudget.setSelection(editTextBudget.getText().toString().length());
                InputMethodManager inputManager = (InputMethodManager)editTextBudget
                        .getContext()
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                new MaterialDialog.Builder(getActivity())
                        .setTitle("请输入您的预算")
                        .setContentView(view1)
                        .setPositiveButton("确定", new MaterialDialog.OnClickListener() {
                            @Override
                            public boolean onClick(DialogInterface dialog, int which) {
                                if(editTextBudget.getText().toString().isEmpty()){
                                    Toast.makeText(getActivity(),"预算不能为空", LENGTH_SHORT).show();
                                    return true;
                                }else if(editTextBudget.getText().toString().equals("0")){
                                    Toast.makeText(getActivity(),"预算不能为0", LENGTH_SHORT).show();
                                    return true;
                                }else{
                                    //Toast.makeText(getActivity(),"预算设置成功",Toast.LENGTH_SHORT).show();
                                    PrefUtils.setBudget(editTextBudget.getText().toString());
                                    onShowBudget.setSummary(editTextBudget.getText().toString() + "元");
                                    application.refresh();
                                }
                                return false;
                            }
                        }).setNegativeButton("取消",null)
                        .show();
                return false;
            }
        });
        islocked.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                Intent intent;
                if(!PrefUtils.getLocked()){
                    intent = new Intent(getActivity(), LockSettingActivity.class);
                }else {
                    LockActivity.isLogin = false;
                    intent = new Intent(getActivity(), LockActivity.class);

                }
                startActivity(intent);
                return false;
            }
        });

        guide.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                GuideActivity.isSettingIn = true;
                Intent intent = new Intent(getActivity(), GuideActivity.class);
                startActivity(intent);
                //getActivity().finish();
                return false;
            }
        });

        islocked.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object o) {
                if(PrefUtils.getLocked()){
                    islocked.setSummary("当前：开启");
                }else {
                    islocked.setSummary("当前：关闭");
                }
                return false;
            }
        });

        //Dialog budgetDialog = onShowBudget.getDialog();
        checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

            /**
             * @param preference The changed Preference.
             * @param newValue   The new value of the Preference.
             * @return True to update the state of the Preference with the new value.
             */
            //SharedPreferences preferences;
            //SharedPreferences.Editor editor;
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {

                boolean checked = Boolean.valueOf(newValue.toString());
                //Context ctx = SettingActivity;
                //preferences=getSharedPreferences("crazyit",MODE_PRIVATE);

                //PrefUtils.continuous_sticker(true);
                application.refresh();
                if(application.isContinuousSticker())
                {
                    application.setContinuousSticker(false);

                }
                else
                {
                    application.setContinuousSticker(true);
                    //启动service
                    
                }
                //Context
                //SharedPreferences sp = getSharedPreferences("SP", MODE_PRIVATE);
               //Logger.d("Pref " + preference.getKey() + " changed to " + newValue.toString());
                return true;

            }
        });
        final CheckBoxPreference remindMode = (CheckBoxPreference)getPreferenceManager()
                .findPreference(getString(R.string.save_remind_mode));
        remindMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener(){
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                boolean checked = Boolean.valueOf(newValue.toString());
                //PrefUtils.remind_mode(true);
                application.refresh();
                if(application.isremind())
                {
                    application.setIsremind(false);
                    application.setReminder(false);
                    Toast.makeText(application.getContext(),"定时提醒功能已取消",Toast.LENGTH_SHORT).show();

                }
                else
                {
                    application.setIsremind(true);
                    application.setReminder(true);

                    Toast.makeText(application.getContext(),"定时提醒功能已开启",Toast.LENGTH_SHORT).show();
                }
                return true;
            }
        });



       // notify();



        final Preference editBudget =(Preference)getPreferenceManager().findPreference(getString(R.string.budget));
        editBudget.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                EditTextPreference editbudget = (EditTextPreference)getPreferenceManager().findPreference(getString(R.string.budget));
                String s= editbudget.getEditText().getText().toString();
                //String s= String.valueOf(application.getBudget());
                String format = null;
                format = editbudget.getSummary().toString();
                editbudget.setSummary(s+"元");
                application.setBudget(s);
                //System.out.println(application.getBudget());
                return true;
            }

        });

//        editBudget.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
//            @Override
//            public boolean onPreferenceClick(Preference preference) {
//                final EditTextPreference editbudget = (EditTextPreference)getPreferenceManager().findPreference(getString(R.string.budget));
//                String s= editbudget.getText();
//                //String s= String.valueOf(application.getBudget());
//                String format = null;
//                format = editbudget.getSummary().toString();
//                editbudget.setSummary(s+"元");
//                application.refresh();
//                System.out.println(application.getBudget());
//                return true;
//
//            }
//        });

//        editbudget.setOnPreferenceChangeListener(new EditTextPreference(){
//
//        });
        //editbudget.setWidgetLayoutResource(R.layout.textview_layout);
        //editbudget.getWidgetLayoutResource();
        //editbudget.getEditText();
        //format = preference.getSummary().toString();
        //editbudget.setSummary(format.replace("{v}", newValue==null?"null":newValue.toString()));

        usersSetting.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
//                PrefUtils.setLogin(false);
                if(!PrefUtils.getLogin()){
                    Toast.makeText(getActivity(),"请先登录", LENGTH_SHORT).show();
                    final EditText text;
                    LayoutInflater inflater = LayoutInflater.from(getActivity());
                    View view1 = inflater.inflate(R.layout.dialog_reg,null);
                    text = (EditText) view1.findViewById(R.id.phone_input_ori);
                    text.requestFocus();
                    InputMethodManager inputManager = (InputMethodManager)text
                            .getContext()
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                    text.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                        }

                        @Override
                        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                            if (charSequence == null || charSequence.length() == 0) return;
                            StringBuilder sb = new StringBuilder();
                            for (int loop = 0; loop < charSequence.length(); loop++) {
                                if (charSequence.charAt(0) == '-' || loop != 3 && loop != 8 && charSequence.charAt(loop) == '-') {
                                    continue;
                                }
                                else {
                                    sb.append(charSequence.charAt(loop));
                                    if ((sb.length() == 4 || sb.length() == 9) && sb.charAt(sb.length() - 1) != '-') {
                                        sb.insert(sb.length() - 1, '-');
                                    }
                                }
                            }
                            if (!sb.toString().equals(charSequence.toString())) {
                                int index = i + 1;
                                if (sb.charAt(i) == '-') {
                                    if (i1== 0) {
                                        index++;
                                    } else {
                                        index--;
                                    }
                                } else {
                                    if (i1 == 1) {
                                        index--;
                                    }
                                }
                                text.setText(sb.toString());
                                text.setSelection(index);
                            }
                        }

                        @Override
                        public void afterTextChanged(Editable editable) {

                        }


                    });
                    new MaterialDialog.Builder(getActivity())
                            .setTitle("登录/注册")
                            .setContentView(text)
                        /*.setLayout(0.8f,0.3f)*/
                            .setPositiveButton("确定", null)
                            .setNegativeButton("取消", null)
                            .setPositiveButton(new MaterialDialog.OnClickListener() {
                                @Override
                                public boolean onClick(DialogInterface dialog, int which) {
                                    //获取不带-的电话号码
                                    phone = text.getText().toString().replaceAll("-","");
                                    System.out.println(phone);
                                    if(phone.length() < 11){
                                        Toast.makeText(getActivity(), "号码格式不正确", LENGTH_SHORT).show();
                                        return true;//输入不成功不退出
                                    }else {
                                        // TODO: 2017/5/29 注册或者登录成功后需要进入新的界面
//                                        Toast.makeText(getApplicationContext(), "输入成功", Toast.LENGTH_SHORT).show();
                                        registerOrLogin(phone);
                                        //登录状态改变
                                        PrefUtils.setLogin(true);
                                        return false;
                                    }
                                }
                            }).show();
                }else{
                    Intent intent  = new Intent(getActivity(),UserSettingActivity.class);
                    startActivity(intent);
                }
                return false;
            }
        });

        suggestion.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                final EditText text1;
                final EditText text2;
                LayoutInflater inflater = LayoutInflater.from(getActivity());


                View view = inflater.inflate(R.layout.dialog_suggestion,null);
                text1 = (EditText) view.findViewById(R.id.contact);
                text2 = (EditText) view.findViewById(R.id.suggestion);

                text1.requestFocus();
                InputMethodManager inputManager1 = (InputMethodManager)text1
                        .getContext()
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager1.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                     new MaterialDialog.Builder(getActivity())
                            .setTitle("意见反馈")
                            .setContentView(view)
                            .setPositiveButton("确定", null)
                            .setNegativeButton("取消", null)
                             .setPositiveButton(new MaterialDialog.OnClickListener() {
                                 @Override
                                 public boolean onClick(DialogInterface dialog, int which) {
                                     //获取Edittext当中的内容
                                     String contact = text1.getText().toString();
                                     String suggestion = text2.getText().toString();
                                     if(!contact.isEmpty() && suggestion.length() > 15) {
                                         suggestionUpdate(contact,suggestion);
                                     }else{
                                         Toast.makeText(getActivity(), "请完整填写完整联系方式及建议", LENGTH_SHORT).show();
                                         return true;
                                     }
                                     return false;
                                 }
                             })
                            .show();
                return false;
            }
        });
    }
//    意见同步云端数据库
    public void suggestionUpdate(final String contact, final String suggestion){
        new Thread(new Runnable() {
            @Override
            public void run() {
                String sql = "insert into suggestion values('"+contact+"','"+suggestion+"')";
                DBTransaction transaction = DBTransaction.createInstance();
                transaction.connectDB();
                PreparedStatement ps = transaction.prepareStatement(sql);
                try {
                    ps.executeUpdate();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                transaction.closeDB();
            }
        }).start();
    }

//    注册与登录
    public void registerOrLogin(final String phone){
        new Thread(new Runnable() {
            Boolean rs = true;
            public void run() {
                //创建事务实例并连接
                DBTransaction transaction = DBTransaction.createInstance();
                PreparedStatement ps = null;
                //事务连接
                transaction.connectDB();
                //设置不自动提交
                transaction.setAutoCommit(false);
                //插入数MqSQL的专用语句
                String ct;
                //查询电话号码是否已经注册
                String sphone = "SELECT phone FROM `userInfo` WHERE phone='"+ phone +"'";
                //定义uid的字符，以免后面uid无返回值时，执行出错
                String uid = null;
                //获取用户信息分配的uid的查询语句
                String getuid = "SELECT uid FROM userInfo WHERE phone='"+ phone +"'";
                //查询电话号码
                ResultSet phoneResultSet = transaction.executeQuery(sphone);
                try{
                    //用户未注册处理操作
                    if (!phoneResultSet.next()){
                        //插入用户信息的查询语句
                        ct = "INSERT INTO userInfo(phone) VALUES('"+ phone +"')";
                        //向数据库中插入注册的电话号码（完成注册）,并获得注册结果
                        ps = transaction.prepareStatement(ct);
                        rs = ps.execute();
                        //TODO:获取注册IP地址，初定于调用某接口并直接使用json获取
//                      InetAddress address = InetAddress.getLocalHost();
//                      String hostAddress = address.getHostAddress();
//                      Toast.makeText(RegisterActivity.this, hostAddress, Toast.LENGTH_LONG).show();
                        //向数据库提交查询语句，并返回结果集
                        ps = transaction.prepareStatement(getuid);
                        ResultSet uidGetResultSet = ps.executeQuery();
                        //ResultSet uidGetResultSet = transaction.executeQuery(ct);
                        //定义uid的字符，以免后面uid无返回值时，执行出错
                        while(uidGetResultSet.next()){
                            uid  = uidGetResultSet.getString("uid");
                        }
//                        登录已成功,存储uid以及设置登录状态
                        PrefUtils.setLogin(true);
                        PrefUtils.setUid(uid);
                        //以uid+用户uid为表明创建一张新的用户表，用于存放用户的账目数据
                        ct = "CREATE TABLE uid" +uid+ "( id mediumint(11) primary key AUTO_INCREMENT,cost double NOT NULL, attribution tinyint(4) NOT NULL, detail tinytext, date datetime )";
                        //返回执行结果情况
                        ps = transaction.prepareStatement(ct);
                        rs = ps.execute();
                        //rs = transaction.execute(ct);
                        //至此注册事务全部完成，提交
                        transaction.commit();

                        //安卓不允许子线程修改UI因此再完成调用和存储之后需要回到主线程更新UI.复写runOnUiThread即可
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (!rs) {
                                    Toast.makeText(getActivity(), "注册成功", Toast.LENGTH_LONG).show();
                                } else {
                                    Toast.makeText(getActivity(), "该号码已注册", Toast.LENGTH_LONG).show();
                                }
                            }
                        });
                    }else{
                        ps = transaction.prepareStatement(getuid);
                        ResultSet uidGetResultSet = ps.executeQuery();
                        while(uidGetResultSet.next()){
                            uid  = uidGetResultSet.getString("uid");
                        }
                        PrefUtils.setLogin(true);
                        PrefUtils.setUid(uid);
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                    Toast.makeText(getActivity(), "登录成功", Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                } catch (SQLException e) {
                    transaction.rollback();
                    e.printStackTrace();
                }
                transaction.closeDB();
            }
        }).start();

    }

    @Override
    public void onResume() {
        if(PrefUtils.getLocked()){
            islocked.setSummary("当前：开启");
        }else {
            islocked.setSummary("当前：关闭");
        }
        String s = String.valueOf(PrefUtils.getBudget());
        if(!s.equals("0")){
            onShowBudget.setSummary( s +"元");
        }
        super.onResume();
    }
}
